package com.miaosha.controller;


import com.miaosha.error.EnumError;
import com.miaosha.error.ErrorException;
import com.miaosha.model.OrderModel;
import com.miaosha.model.UserInformationModel;
import com.miaosha.response.CommonResponse;
import com.miaosha.service.OrderService;
import org.apache.catalina.mbeans.UserMBean;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller()
@RequestMapping("/order")
public class OrderController extends BaseController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping(value = "/createOrder", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORM})
    @ResponseBody
    public CommonResponse createOrder(@RequestParam(name = "productId")Integer productId,
                                      @RequestParam(name = "amount")Integer amount,
                                      @RequestParam(name = "promoId", required = false)Integer promoId) throws ErrorException {
        // 获取用户信息
        Boolean isLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (isLogin == null || !isLogin){
            throw new ErrorException(EnumError.USER_NOT_LOGIN, "用户还未登录，不能下单");
        }
        UserInformationModel userInformationModel = (UserInformationModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");
        OrderModel orderModel = orderService.createOrder(userInformationModel.getId(), productId, promoId, amount);
        return CommonResponse.create(null);
    }
}
